package zhupf.test.threadTest;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 需求：A打印5次，B打印10次，C打印15次,，顺序A->B->C
 * 循环5次
 */

class Print{
    private int  number = 0;
    private final int PRINT_A=0;
    private final int PRINT_B=1;
    private final int PRINT_C=2;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void printA(){
        lock.lock();
        //判断
        try {
            while (number!=PRINT_A){
                condition1.await();
            }
            //干活
            for(int i = 1 ;i<=5;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            //通知
            number = PRINT_B;
            condition2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        //判断
        try {
            while (number!=PRINT_B){
                condition2.await();
            }
            //干活
            for(int i = 1 ;i<=10;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            //通知
            number = PRINT_C;
            condition3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        //判断
        try {
            while (number!=PRINT_C){
                condition3.await();
            }
            //干活
            for(int i = 1 ;i<=15;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            //通知
            number = PRINT_A;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

public class ConditionDemo {
    public static void main(String[] args) {
        Print print = new Print();
        new Thread(()->{for(int i = 0;i<5;i++) print.printA();},"A").start();
        new Thread(()->{for(int i = 0;i<5;i++) print.printB();},"B").start();
        new Thread(()->{for(int i = 0;i<5;i++) print.printC();},"C").start();
    }
}
